<template>
  <div class="container box" v-loading='loading'>
    <div class="contain" v-if='!toAuthor'>
      <!-- 查询表单 -->
      <div class="search_form" ref="searchCard">
        <div></div>
        <div>
          <el-tooltip class="item" effect="dark" content="新增" placement="left" v-if="menuArr.includes('授权管理新增')">
            <el-button icon="el-icon-plus" size="mini" @click="addAuthorize"></el-button>
          </el-tooltip>
        </div>
      </div>

      <!-- 表格 -->
      <template>
        <BaseTable :data="cargotableData" :columns="cargotableDataColumns" :tableHeight="tableHeight" :pagination="false" :loading="tableLoading"></BaseTable>
      </template>

      <div class="page">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="queryInfo.page" :page-sizes="[10, 15, 30, 45]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="queryInfo.totalNum"></el-pagination>
      </div>
      <!-- 新增/编辑授权 -->
      <el-drawer :title="isAddAuthorize?'新增授权':'重新授权'" :before-close="handleClose" :visible.sync="authorizeVisible" direction="rtl" size:="30%">
        <div class="demo-drawer__content" style="padding: 20px;">
          <el-form :model="authorizeForm" ref="formRef" :rules="formRules">

            <!-- <el-form-item label="有效日期：" :label-width="formLabelWidth" prop="validTime">
              <el-date-picker :popper-class="'currentDatePickerClass'" :picker-options="pickerOptions" size="small" v-model="authorizeForm.validTime" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd hh:mm:ss">
              </el-date-picker>
            </el-form-item> -->
            <el-form-item label="授权系统：" :label-width="formLabelWidth" prop="systemName">
              <el-input size="small" v-model="authorizeForm.systemName" @blur='numChange'></el-input>
            </el-form-item>
            <el-form-item label="系统编号：" :label-width="formLabelWidth" prop="systemCode">
              <el-input disabled size="small" v-model="authorizeForm.systemCode" ></el-input>
            </el-form-item>
            <el-form-item label="授权url：" :label-width="formLabelWidth" prop="authorizeUrl">
              <el-input size="small" v-model="authorizeForm.authorizeUrl"></el-input>
            </el-form-item>
            <el-form-item label="回调url：" :label-width="formLabelWidth" prop="callbackUrl">
              <el-input size="small" v-model="authorizeForm.callbackUrl"></el-input>
            </el-form-item>
          </el-form>
          <div class="demo-drawer__footer">
            <el-button size="small" type="primary" @click="saveAuthorizeForm" :loading="btnLoading">{{ btnLoading ? '提交中 ...' : '保 存' }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
    <div id="iframe-container" v-if="toAuthor">
      <iframe :src="link" scrolling="auto" frameborder="0" id="iframe" ref="iframe" style="width:100%;height:100%;"></iframe>
    </div>
    <!-- <el-dialog :visible="isModal" width="30%" center="" :close-on-click-modal='false' :close-on-press-escape='false' :show-close='false'>
      <i class="iconfont icon-icon-061" style="font-size:48px;color:green"></i>
      <div>授权成功{{count}}后跳转授权页面</div>
    </el-dialog> -->
  </div>
</template>

<script>
import BaseTable from '@/components/BaseTable'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Utils from "@/libs/Utils.js"
export default {
  components: {
    BaseTable,
  },
  data() {
    return {
      menuArr:[],
      loading:false,
      count: 3,//多少秒后关闭页面
      upDataAuthor: {
        id: '',
        account: '',
        password: '',
        authorDate: ''
      },
      link: '',//跳转地址
      toAuthor: false,//是否跳转授权页
      oldVal: {},
      cargotableDataColumns: [
         { prop: 'createName', label: '操作人' },
        { prop: 'systemName', label: '授权系统' },

        { prop: 'authorizeName', label: '授权账号' },
        { prop: 'authorizeTime', label: '授权时间' },
        { prop: 'validTime', label: '有效日期' },
        {
          prop: 'isAuthorize',
          label: '是否授权',

          render(h, params) {
            if (params.row.isAuthorize == '0') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                },
                domProps: {
                  innerHTML: '已授权'
                }
              })
            } else if (params.row.isAuthorize == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未授权'
                }
              })
            }
          }
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h('el-button', {
                props: {
                  size: 'mini'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  innerHTML: params.row.isAuthorize == "0" ? `<span style='color:#E02020;display: ${this.menuArr.includes('取消授权')?"block":"none"}'><i class='iconfont icon-shougong'></i><span  style='padding-left:5px;'>取消授权</span></span>` : `<span style='color:#0B6CD6;display: ${this.menuArr.includes('立即授权')?"block":"none"}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>立即授权</span></span>`

                },
                on: {
                  click: () => {
                    this.updateAuthorize(params.row.isAuthorize, params.row.id)
                  }
                }
              }),
              h(
                'el-button', {
                props: {
                  size: 'mini'
                },

                domProps: {
                  // innerHTML: ` <i class="iconfont icon-liebiaotubiao_liebiaobianji" style="color:#2166B2"></i>编辑`
                  innerHTML: `<span style="display: ${this.menuArr.includes('授权管理删除')?"block":"none"}"><i class='iconfont icon-1-08'></i><span  style='padding-left:2px;'>删除</span></span>`
                },
                on: {
                  click: () => {
                    click: this.zDelete(params.row, params.row.id)
                  }
                }
              }
              )
            ])
          }
        }
      ],
      cargotableData: [],
      // tableHeight: window.innerHeight - 200,
      tableLoading: false,
      isAddAuthorize: false,
      btnLoading: false,
      formRules: {
        // validTime: [{
        //   required: true,
        //   message: '请选择有效日期',
        //   trigger: 'blur'
        // }],
        systemName: [{
          required: true,
          message: '请输入授权系统',
          trigger: 'blur'
        }],
        authorizeUrl: [{
          required: true,
          message: '请输入授权url',
          trigger: 'blur'
        }],
        callbackUrl: [{
          required: true,
          message: '请输入回调url',
          trigger: 'blur'
        }],
      },
      authorizeVisible: false,
      formLabelWidth: '130px',
      // 查询表单
      searchForm: {
        // createName: '',
        // releaseState: ''
      },
      authorizeForm: {
        // validTime: '',
        systemCode:'',
        systemName: '',
        authorizeUrl: '',
        callbackUrl: '',
      },
      // 角色列表数据
      queryInfo: {
        // 当前页数
        page: 1,
        //每页显示多少数据
        pagesize: 10,
        totalNum: 1
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
    }
  },

  methods: {
    //获取系统标号
    numChange(){
      this.$http('/${this.$ServiceName}/api/external/public/autorefer',{params:{name:this.authorizeForm.systemName}}).then(res=>{
        this.authorizeForm.systemCode = res.data.data
      })
    },
    //删除
    zDelete(row, id) {
      this.$confirm('确定取消授权？此操作无法撤回')
        .then(_ => {
          this.$http.delete(
            `/${this.$ServiceName}/api/external/authorization/${this.$version}/deletebyid`, {
            params: {
              id: id
            }
          }
          ).then(res => {
            if (res.data.success) {
              this.getDataList()
              this.$message.success(res.data.msg)
            } else {
              this.$message.error(res.data.msg)
            }
          })
            .catch(_ => { })

        })
    },
    //接受ifram子传父事件的方法
    getIframChild(e) {
      let that = this
      if (e.data.flagData != undefined && e.data.flagData == 'author') {
        console.log(e);
        this.upDataAuthor.account = e.data.account
        this.upDataAuthor.password = e.data.password
        this.upDataAuthor.authorDate = e.data.authorDate
        this.updateAuthor()

      }else if (e.data.flag == 'success') {
        this.link = `http://192.168.75.168:999/iotfc/${e.data.url}`
        // this.link = 'http://127.0.0.1:5500/page/toAuthorization/toAuthorization.html?cont=ssdfa11'
        // this.link = `http://127.0.0.1:5500/page/toAuthorization/toAuthorization.html?account=${e.data.account}&password=${e.data.password}`
        // this.sendMessage()
        // this.link = `http://192.168.75.168:999/iotfc/${e.data.url}?account=${e.data.account}&password=${e.data.password}`
        // this.link = 'http://127.0.0.1:5500/page/toAuthorization/toAuthorization.html'
        // this.toAuthor = false
        // this.$nextTick(() => {
        //   this.toAuthor = true
        // setTimeout(()=>{
        //   this.sendMessage()
        // },10)
        // })
      }
    },
    //ifram发送组件
    sendMessage() {
      // let sonIframe= this.$refs.iframe
      // let info = 'xxxxxxx'
      // sonIframe.contentWindow.postMessage(info, '*');
      var myframe = document.getElementById('iframe') //获取iframe
      console.log(myframe);
      console.log(myframe.contentWindow);
      let childDomain = 'http://127.0.0.1:5500'
      myframe.contentWindow.postMessage({ data: 'parent' }, '*');//childDomain是子页面的源（协议+主机+端口号）

    },
    // option(){
    //   disabledDate:(time)=> {
    //     return time.getTime() <= Date.now()
    //   }
    // },
    //新增
    addAuthorize() {
      this.isAddAuthorize = true
      this.authorizeVisible = true
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
        this.oldVal = JSON.parse(JSON.stringify(this.authorizeForm))
      })
    },
    //新更新接口
    updateAuthor() {
      this.loading = true
      this.link = 'http://192.168.75.168:999/iotfc/authorize/ppmcloud'
      this.$http.put(
        `/${this.$ServiceName}/api/external/authorization/v1/updatenew`, this.upDataAuthor
      ).then(res => {
        this.loading = false
        this.toAuthor = false
        if (res.data.success) {
          this.getDataList()
          this.$message.success('授权成功')
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    updateAuthorize(isAuthorize, id) {
      if (isAuthorize == '0') {
        this.$confirm('确定取消授权？此操作无法撤回')
          .then(_ => {
            this.deleteAuthorize(id)
          })
          .catch(_ => { })
      } else {    //重新授权
        //  this.undateAuthorize(id)
        this.toAuthor = true
        this.upDataAuthor.id = id
      }
    },
    //重新授权
    undateAuthorize(rid) {
      this.$http.get(
        `/${this.$ServiceName}/api/external/authorization/v1/getauthorizebyid?id=${rid}`,
      ).then(res => {
        if (res.data.success) {
          let data = res.data.data
          this.authorizeForm.validTime = data.validTime ? data.validTime : ''
          this.authorizeForm.systemName = data.systemName
          this.authorizeForm.authorizeUrl = data.authorizeUrl
          this.authorizeForm.callbackUrl = data.callbackUrl
          this.authorizeForm.id = data.id
          this.isAddAuthorize = false //为编辑状态
          this.authorizeVisible = true //打开模态框
          this.oldVal = JSON.parse(JSON.stringify(this.authorizeForm))

        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    handleClose(done) {
      if (!Utils.compareData(this.oldVal, this.authorizeForm)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    },
    //取消授权
    deleteAuthorize(rid) {
      let params = { 'id': rid }
      this.$http.put(
        `/${this.$ServiceName}/api/external/authorization/v1/deleteauth?id=${rid}`,
      ).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.msg)
          this.getDataList()
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    //搜索
    async searchClick() {
      this.queryInfo.page = 1
      this.getDataList()
    },
    //获取用户table信息
    async getDataList() {
      this.tableLoading = true
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/authorization/${this.$version}/queryall?startpage=${this.queryInfo.page}&pagesize=${this.queryInfo.pagesize}`, { params: this.searchForm }
      )
      if (res.data.code != '0000') {
        this.cargotableData = []
        this.tableLoading = false
      }
      this.cargotableData = res.data.data.pages
      this.queryInfo.totalNum = res.data.data.totalNum
      this.queryInfo.page = res.data.data.pageNum
      this.queryInfo.pagesize = res.data.data.pageSize
      this.tableLoading = false
    },
    saveAuthorizeForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.isAddAuthorize) {
            this.addAuthorizeFun()
          } else {
            this.updateAuthorizeFun()
          }
        }
      })
    },
    addAuthorizeFun() {
      let params = this.authorizeForm
      // params.token = sessionStorage.getItem('token')
      this.$http.post(
        `/${this.$ServiceName}/api/external/authorization/${this.$version}/insert`, params
      ).then(res => {
        if (res.data.success) {
          this.authorizeVisible = false
          this.getDataList()
          this.$message.success(res.data.msg)
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    updateAuthorizeFun() {
      let params = this.authorizeForm
      // params.token = sessionStorage.getItem('token')
      this.$http.put(
        `/${this.$ServiceName}/api/external/authorization/${this.$version}/update`, params
      ).then(res => {
        if (res.data.success) {
          this.authorizeVisible = false
          this.getDataList()
          this.$message.success(res.data.msg)
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    // 每页显示的条数
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getDataList()
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryInfo.startpage = val
      this.getDataList()
    },
  },
  computed: {
    tableHeight() {
      return this.$store.state.tableHeight
    },
  },
  async activated() {
    //接收跨域信息
    window.addEventListener('message', this.getIframChild, true);
    var menuArr = []
    var menuId = ""
    if(localStorage.getItem("menuArr")){
      menuArr = JSON.parse(localStorage.getItem("menuArr"))
    }
    menuArr.map(item=>{
      item.children.map(v=>{
        if(window.location.href.includes(v.url)){
          menuId = v.id
        }
      })
    })

    if(menuId){
      this.menuArr = []
      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`,{ timeout: 30000,})
              .then(res => {
                res.data.data.map(item=>{
                  this.menuArr.push(item.resourceName)
                })
              }).catch((error)=>{})
    }
    if (this.$store.state.app.searchResouce == "menu") {
        this.toAuthor = false
        this.link = 'http://192.168.75.168:999/iotfc/authorize/ppmcloud'
        // this.link = 'http://127.0.0.1:5500/page/login/login.html'
        this.getDataList()
    }

  },
  deactivated() {
    window.removeEventListener("message", this.getIframChild, true);
  }
}
</script>
<style lang='less' scope>
.loadingClass /deep/ .el-icon-success {
  font-size: 108px;
  color: green;
  z-index: 100;
}
.loadingClass /deep/ .el-loading-text {
  font-size: 22px;
  color: #ffffff;
}
.currentDatePickerClass
  > .el-picker-panel__footer
  > .el-button--text:first-child {
  display: none;
}
</style>
<style lang="less" scoped>
#iframe-container {
  width: 100%;
  height: 100%;
}
/deep/ .el-table th:last-child {
  border-left: none;
}
/deep/.el-table {
  max-height: none !important;
}

/deep/.el-tabs__item:focus.is-active.is-focus:not(:active) {
  box-shadow: none !important;
}
/deep/.el-tabs__nav-wrap {
  padding: 0 20px;
  box-sizing: border-box;
}
/deep/.el-drawer__body > * {
  height: 100%;
}
/deep/ .el-button--primary {
  background-color: #338ce8;
  border-color: #338ce8;
}
/deep/.el-tabs__content {
  position: initial !important;
}
/deep/ .el-collapse-item__header {
  background: #f5f7fa;
}
/deep/ .el-table thead {
  font-size: 14px;
  font-family: Microsoft YaHei;
  color: #606266;
}

/deep/.el-pagination.is-background .btn-next,
/deep/ .el-pagination.is-background .btn-prev,
/deep/ .el-pagination.is-background .el-pager li {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 3px;
  border-radius: 3px;
}

.container {
  height: 100%;
  .form_card {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  /deep/.el-card__body {
    width: 100%;
    padding: 0;
    border-radius: 0;
  }
  .page {
    background: #ffffff;
    text-align: right;
    border-radius: 0 0 4px 4px;
    padding: 5px 20px;
  }

  .editBtn,
  .deleteBtn {
    color: #1684f6;
    border-color: transparent;
    background: transparent;
  }
  //分页
  .card_pagination {
    text-align: right;
  }
  .el-scrollbar .el-scrollbar__wrap .el-scrollbar__view {
    white-space: nowrap;
  }
}
.el-table {
  margin-bottom: 0 !important;
}
.el-table td {
  padding: 10px 0;
  text-align: left;
}
// 查询表单start
.search_form {
  background-color: #fff;
  color: #303133;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;

  /deep/.el-input {
    width: 150px;
  }
}
.box {
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}
/deep/.el-date-editor.el-input {
  width: 100%;
}
</style>

